from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError, PyMongoError

# 连接字符串
connection_string = 'mongodb://xkb_prod_backup:xkb_prod_backup@dds-2zec1c50c123cf241234-pub.mongodb.rds.aliyuncs.com:3717'

client = None  # 初始化为 None

try:
    # 尝试连接到 MongoDB
    client = MongoClient(connection_string, serverSelectionTimeoutMS=5000)
    print("成功连接到 MongoDB")

    # 指定数据库
    db_name = 'xkb_prod_backup'
    db = client[db_name]
    print("正在查询数据库:", db_name)

    # 查询条件
    query = {'orderNo': 'J1645045741379'}

    # 查询 orders 集合
    orders_collection = db['orders']
    orders_documents = list(orders_collection.find(query))
    if orders_documents:
        print(f"'orders' 集合中找到 {len(orders_documents)} 个符合条件的文档:")
        for doc in orders_documents:
            print(doc)
    else:
        print("'orders' 集合中没有找到符合条件的文档")

    # 查询 ordersDetail 集合
    orders_detail_collection = db['ordersDetail']
    orders_detail_documents = list(orders_detail_collection.find(query))
    if orders_detail_documents:
        print(f"'ordersDetail' 集合中找到 {len(orders_detail_documents)} 个符合条件的文档:")
        for doc in orders_detail_documents:
            print(doc)
    else:
        print("'ordersDetail' 集合中没有找到符合条件的文档")

except ServerSelectionTimeoutError as e:
    print("连接失败: 服务器选择超时", e)
except PyMongoError as e:
    print("连接失败: PyMongo错误", e)
finally:
    if client is not None:
        client.close()
        print("连接已关闭")